package freedom.solution.app.prueba;


import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

import freedom.solution.app.restaurante.imagedb.*;



import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import freedom.solution.app.restaurante.datatypes.DBMesa;
import freedom.solution.app.restaurante.datatypes.DBProducto;
import freedom.solution.app.restaurante.datatypes.DBclass;
import freedom.solution.app.restaurante.service.Conexion;

import freedom.soluttion.app.restaurante.MainActivity;
import freedom.soluttion.app.restaurante.R;
import freedom.soluttion.app.restaurante.MainActivity.ImageAdapter;


public class MenuPrincipalActivity2 extends Activity {
	byte[] foto1;
	GridView MyGrid;
    private ProgressDialog pDialog;
    String [] mesaNum ;
    String [] mesaId ;
    int [] mesaEstado;
    ArrayList<HashMap<String,String>> mesaList;
    ImageAdapter adapter = null;
	private static final String TAG_ID_MESA="id_mesa";
	private static final String TAG_ID_ESTADO="id_estado";
	private static final String TAG_CAPACIDAD="capacidad";
	private static final String TAG_NUMERO="numero";
	DBclass dbclass;
	
	 public List<Bitmap> av=null;
	 ArrayList<DBMesa>  lista_mesas;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
		setContentView(R.layout.mesas_principal);
		dbclass = new DBclass(getApplicationContext());
		mesaList = new ArrayList<HashMap<String,String>>();
		lista_mesas= new ArrayList<DBMesa>();
		mesaNum= new String [20];
	    mesaId= new String [20];
	    mesaEstado= new int [20];
        adapter = new ImageAdapter(this);
    	byte[] image = Utilities.getBytes(BitmapFactory.decodeResource(getResources(), R.drawable.food1));
    
    	 dbclass.actualizarFotoProducto("3", image);
         dbclass.actualizarFotoProducto("4", image);
         dbclass.actualizarFotoProducto("5", image);
         dbclass.actualizarFotoProducto("6", image);
         dbclass.actualizarFotoProducto("7", image);
        ArrayList<DBProducto>  productos= new ArrayList<DBProducto>();
		productos= dbclass.obtenerProductos();
		
      new asyncmesas().execute(); 
    }
    
    
    public class ImageAdapter extends BaseAdapter
	{
		Context MyContext;
		
		public ImageAdapter(Context _MyContext)
		{
			MyContext = _MyContext;
		}
		
	
		public int getCount() 
		{
		return	lista_mesas.size();
		}

		
		public View getView(int position, View convertView, ViewGroup parent) 
		{
			((GridView)parent).setNumColumns(GridView.AUTO_FIT);
			
			View MyView = convertView;

			ViewHolder holder;

			
			if ( convertView == null )
			{
				LayoutInflater li = getLayoutInflater();
				MyView = li.inflate(R.layout.mesa, null);
			
		

                holder=new ViewHolder();
 				
 	 			holder.descripcion=(TextView)MyView.findViewById(R.id.grid_item_text);
 	 			holder.image=(ImageView)MyView.findViewById(R.id.grid_item_image);

		
 	 			MyView.setTag(holder);
			}
			else
			{
				holder=(ViewHolder)convertView.getTag();

				MyView.setTag(holder);
					

			}
			
			
			
			
			holder.descripcion.setText("Mesa "+ mesaNum[position] );
	
			if(mesaEstado[position]==1){
			
			holder.image.setImageResource(R.drawable.table);}
			else
				holder.image.setImageResource(R.drawable.table2);
				
			
			return MyView;
		}

	
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return null;
		}

		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return 0;
		}
		
		public class ViewHolder{
			TextView descripcion;
			ImageView image;
		}
	}
    
    class asyncmesas extends AsyncTask< String, String, String > {
	   	 
    	String user,pass;
        protected void onPreExecute() {
        	//para el progress dialog
            pDialog = new ProgressDialog(MenuPrincipalActivity2.this);
            pDialog.setMessage("Cargando Mesas....");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }
 
        protected String doInBackground(String... args) {
            // Building Parameters
        
		 lista_mesas= dbclass.getMesas();
         int i=0;
	
    		try			
    		{	 
    			
    				 
    				
    			 Iterator<DBMesa> it=lista_mesas.iterator();
				 while ( it.hasNext() ) { 
					  Object objeto = it.next(); 
					  DBMesa dbmesa = (DBMesa)objeto; 
					   
						
					   mesaNum[i]=dbmesa.getNumero();
					mesaId[i]=dbmesa.getId_mesa()+"";
					mesaEstado[i]=dbmesa.getId_estado();
					i++;
				}
    		    
    		        
    			
    		} 
    		catch (Exception e) 
    		{
    			//Toast.makeText(this, "No existe categorias", Toast.LENGTH_LONG).show();
    		} 
            return null;
        }
       
		/*Una vez terminado doInBackground segun lo que halla ocurrido 
		pasamos a la sig. activity
		o mostramos error*/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog after getting all albums
            pDialog.dismiss();
            // updating UI from Background Thread
            runOnUiThread(new Runnable() {
                public void run() {
                    /**
                     * Updating parsed JSON data into ListView
                     * */
                	
               
                 
                	 MyGrid = (GridView)findViewById(R.id.mesas_principal);
                	  MyGrid.setAdapter(adapter);
                	 MyGrid.setOnItemClickListener(new OnItemClickListener() {
                          public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
                              //Toast.makeText(context, "" + position, Toast.LENGTH_SHORT).show();
                        		Intent i=new Intent(getApplicationContext(), DetallePedidoActivity.class);
                        		String id_mesaa=mesaId[position];
                        		 i.putExtra("id_mesa", id_mesaa);  
                    				startActivity(i); 
                          }
                      });
                }
            });
 
        }
	}
    
    
   public boolean onCreateOptionsMenu(Menu menu) {
    	
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_principal, menu);
        
        return true;
    }
    
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.mnu_Bebidas:
     
            return true;
        case R.id.mnu_Menu:
        	Intent i=new Intent(getApplicationContext(),CustomizedListView.class);
    	
				startActivity(i); 
            return true;
        case R.id.mnu_EnviarOrden:

            return true;
        case R.id.mnu_Pagar:
      
            return true;
        case R.id.mnu_UnirMesas:
        
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }
    }
